package main

import (
	"context"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"go-nacos-demo/load_balance_nacos/server/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/protobuf/types/known/emptypb"
	"log"
)

func main() {
	// 创建serverConfig
	// 支持多个;至少一个ServerConfig
	serverConfig := []constant.ServerConfig{
		{
			IpAddr: "192.168.193.128",
			Port:   8848,
		},
	}

	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "97b46c8b-81e6-4614-80fb-4fe5553590ca", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}

	// 创建服务发现客户端的另一种方式 (推荐)
	namingClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfig,
		},
	)
	if err != nil {
		log.Fatalf("初始化nacos失败: %s", err.Error())
	}

	for i := 0; i < 10; i++ {
		// SelectOneHealthyInstance将会按加权随机轮询的负载均衡策略返回一个健康的实例
		// 实例必须满足的条件：health=true,enable=true and weight>0
		instance, err := namingClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
			ServiceName: "test-server",
			GroupName:   "DEFAULT_GROUP",     // 默认值DEFAULT_GROUP
			Clusters:    []string{"DEFAULT"}, // 默认值DEFAULT
		})
		log.Printf("获取到的实例IP:%s;端口:%d", instance.Ip, instance.Port)
		conn, err := grpc.Dial(fmt.Sprintf("%s:%d", instance.Ip, instance.Port), grpc.WithTransportCredentials(insecure.NewCredentials()))
		if err != nil {
			log.Fatalf("监听%s:%d失败:%s", instance.Ip, instance.Port, err.Error())
		}
		client := proto.NewTestClient(conn)
		res, err := client.Test(context.Background(), &emptypb.Empty{})
		if err != nil {
			log.Fatalf("调用TestClient失败: %s", err.Error())
		}
		log.Println(res.Msg)
	}
}
